package com.yanqu.road.server.manger.notice;

import com.yanqu.road.entity.enums.eNoticeType;
import com.yanqu.road.entity.notice.NoticeRecord;
import com.yanqu.road.logic.bussiness.notice.NoticeRecordBussiness;
import com.yanqu.road.server.TempMgr;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通知用户的记录Mgr
 */
public class NoticeRecordMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(NoticeRecordMgr.class.getName());

    /**
     * Map<用户ID，Map<通知类型，通知记录>>
     */
    private static Map<Long, Map<Integer, NoticeRecord>> noticeRecordMap;

    @Override
    public boolean reloadData() throws Exception {
        noticeRecordMap = NoticeRecordBussiness.getNoticeRecordMap();
        return true;
    }

    @Override
    public boolean save() {
        for (Map<Integer, NoticeRecord> tmpMap : noticeRecordMap.values()) {
            for (NoticeRecord record : tmpMap.values()) {
                if (record.isInsertOption()) {
                    NoticeRecordBussiness.addNoticeRecord(record);
                } else if (record.isUpdateOption()) {
                    NoticeRecordBussiness.updateNoticeRecord(record);
                }
            }
        }
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static NoticeRecord getNoticeRecord(long userId, eNoticeType type) {
        if (noticeRecordMap.containsKey(userId) && noticeRecordMap.get(userId).containsKey(type.getValue())) {
            return noticeRecordMap.get(userId).get(type.getValue());
        }
        return null;
    }

    /**
     * 添加记录，如果存在则返回false
     */
    public static boolean addNoticeRecord(long userId, eNoticeType type, long time) {
        if (noticeRecordMap.containsKey(userId) && noticeRecordMap.get(userId).containsKey(type.getValue())) {
            return false;
        }
        NoticeRecord noticeRecord = new NoticeRecord();
        noticeRecord.setUserId(userId);
        noticeRecord.setNoticeType(type.getValue());
        noticeRecord.setNotifyTime(time);
        noticeRecord.setInsertOption();
        if (!noticeRecordMap.containsKey(userId)) {
            noticeRecordMap.put(userId, new ConcurrentHashMap<>());
        }
        noticeRecordMap.get(userId).put(type.getValue(), noticeRecord);
        return true;
    }

}
